<?php
/**
 * Excel
 * (model)
 */
namespace App\Util;
use App\Exporter\Util\ArrExporter;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Carbon\Carbon;
use PhpOffice\PhpSpreadsheet\Shared\Date;
class RExcel
{
    public static function importResult($re){
        $res[] = ['行','出错信息'];
        foreach($re as $k => $v){
            if(!$v)continue;
            $res[] = [$k,$v];
        }
        return Excel::download(new ArrExporter($res),'上传结果.csv');
    }

    /**
     * Excel导入 日期格式化
     * @param string $value
     * @param string $format
     * @return Carbon|false|string
     */
    public static function toDateTime(string $value, string $format = 'Y-m-d')
    {
        try {
            return Carbon::instance(Date::excelToDateTimeObject($value))->format($format);
        } catch (\ErrorException $e) {
            return Carbon::createFromFormat($format, $value);
        }
    }

    /**
     * 导出csv文件
     * @param $filename
     * @param $callback
     */
    public static function exportCsv($filename,callable $callback)
    {
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="'.$filename.'.csv"',
        ]);
        $response->setCallback($callback);
        $response->send();
        exit(0);
    }

    /**
     * 读取csv文件
     * @param $file
     * @param bool $isJP
     * @return \Generator
     */
    public static function importCsvFile($file,$isJP = false){
        if($isJP){
            $fp = self::_utf8FOpenReadJP($file);
        }else{
            $fp = fopen($file, 'r');
        }
        try {
            while (!feof($fp)) {
                yield fgetcsv($fp,10000);
            }
        } finally {
            fclose($fp);
        }
    }

    protected static function _utf8FOpenReadJP($file) {
        $subject = iconv('shift-jis', 'UTF-8//IGNORE', file_get_contents($file));
        $fp = fopen("php://memory", "rw");
        fwrite($fp, $subject);
        fseek($fp, 0);
        return $fp;
    }

    /**
     * 读取文件
     * @param      $file
     * @return \Generator
     */
    public static function importFile($file){
        $fp = self::_utf8FOpenRead($file);
        try {
            while (!feof($fp)) {
                yield fgets($fp);
            }
        } finally {
            fclose($fp);
        }
    }

    /**
     * @param $file
     * @param string $outCharset
     * @return false|resource
     */
    protected static function _utf8FOpenRead($file,$outCharset = "UTF-8") {
        $subject = file_get_contents($file);
        $inCharset = mb_detect_encoding($subject,mb_list_encodings());
        if($inCharset != $outCharset){
            $subject = mb_convert_encoding($subject ,$outCharset , $inCharset);
        }
        $fp = fopen("php://memory", "rw");
        fwrite($fp, $subject);
        fseek($fp, 0);
        return $fp;
    }

    public static function importSheet($file){
        $spreadsheet = IOFactory::load($file);
        return $spreadsheet->getActiveSheet()->toArray();
    }

    public static function importSheet1($file){

        $spreadsheet = IOFactory::load($file);

        /*// 获取第一个工作表
        $worksheet = $spreadsheet->getActiveSheet()->toArray();

        // 启用计算引擎
        Calculation::getInstance($spreadsheet)->setCalculationCacheEnabled(true);

        // 遍历工作表中的每个单元格，并尝试计算公式
        foreach ($worksheet->getRowIterator() as $row) {
            foreach ($row->getCellIterator() as $cell) {
                if ($cell->isFormula()) {
                    $cell = $cell->getCalculatedValue();
                }
            }
        }*/

        return $spreadsheet->getActiveSheet()->toArray();
    }

}
